package com.telecomyt.jwportal.activity.message;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.telecomyt.jwportal.R;
import com.telecomyt.jwportal.activity.message.adapter.MessageAdapter;
import com.telecomyt.jwportal.activity.message.bean.MessageBean;
import com.telecomyt.jwportal.base.BaseActivity;
import com.telecomyt.jwportal.base.BasePresenter;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;

public class MessageActivity extends BaseActivity {
    @BindView(R.id.mTextView)
    TextView mTextView;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    addMessage("我是一条新消息~");
                    break;
            }
        }
    };
    @BindView(R.id.mRecyclerView)
    RecyclerView mRecyclerView;
    private MessageAdapter messageAdapter;
    private List<MessageBean> beanList = new ArrayList<>();
    private Timer mTimer = new Timer();
    private boolean isScroll = false;//是否滚动
    private int lastPosition;

    public static void start(Context context) {
        Intent starter = new Intent(context, MessageActivity.class);
        context.startActivity(starter);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_message;
    }

    @Override
    protected void initView() {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        messageAdapter = new MessageAdapter(R.layout.activity_message_items);
        mRecyclerView.setAdapter(messageAdapter);
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                switch (newState) {
                    /*正在拖拽*/
                    case RecyclerView.SCROLL_STATE_DRAGGING:
                        isScroll = true;
//                        isVisibleMessage(false);
                        break;
                    /*滑动停止*/
                    case RecyclerView.SCROLL_STATE_IDLE:
                        RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
                        if (layoutManager instanceof GridLayoutManager) {
                            //通过LayoutManager找到当前显示的最后的item的position
                            lastPosition = ((GridLayoutManager) layoutManager).findLastVisibleItemPosition();
                        } else if (layoutManager instanceof LinearLayoutManager) {
                            lastPosition = ((LinearLayoutManager) layoutManager).findLastVisibleItemPosition();
                        }
                        if (lastPosition == recyclerView.getLayoutManager().getItemCount() - 1) {
                            isScroll = false;
//                            isVisibleMessage(false);
                        }
                        break;
                    /*惯性滑动中*/
                    case RecyclerView.SCROLL_STATE_SETTLING:
                        isScroll = true;
//                        isVisibleMessage(false);
                        break;
                }
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
//                getScollYDistance();//条目总长度

            }
        });
    }


    @Override
    protected void initData() {
        TimerTask mTimerTask = new TimerTask() {
            @Override
            public void run() {
                handler.sendEmptyMessage(1);
            }
        };
        //2s后开始执行，间隔为2s
        mTimer.schedule(mTimerTask, 2000, 2000);
    }

    @OnClick(R.id.mTextView)
    public void onViewClicked() {
        isScroll = false;
//        isVisibleMessage(false);
        mRecyclerView.scrollToPosition(messageAdapter.getData().size() - 1);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mTimer.cancel();

    }

    @Override
    protected BasePresenter creatPresenter() {
        return null;
    }


    private void addMessage(String msg) {
        beanList.clear();
        MessageBean bean = new MessageBean();
        bean.setMessage(msg);
        beanList.add(bean);
        messageAdapter.addData(beanList);
        if (messageAdapter.getData().size() == 4) {
            setHight();
        }
        if (!isScroll) {
            mRecyclerView.scrollToPosition(messageAdapter.getData().size() - 1);
        }
//        else {
//            isVisibleMessage(false);
//        }
    }

    /**
     * @date: 2020/9/7
     * @author: chengDa
     * @description: 设置条目高度
     */
    private void setHight() {
        RecyclerView.Adapter adapter = mRecyclerView.getAdapter();
        int itemCount = adapter.getItemCount();
        if (itemCount > 0) {
            RecyclerView.ViewHolder holder = adapter.createViewHolder(mRecyclerView, adapter
                    .getItemViewType(0));
            adapter.onBindViewHolder(holder, 0);
            holder.itemView.measure(
                    View.MeasureSpec.makeMeasureSpec(mRecyclerView.getWidth(), View.MeasureSpec.EXACTLY),
                    View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
            holder.itemView.layout(0, 0, holder.itemView.getMeasuredWidth(),
                    holder.itemView.getMeasuredHeight());
            holder.itemView.setDrawingCacheEnabled(true);
            holder.itemView.buildDrawingCache();
            int measuredHeight = holder.itemView.getMeasuredHeight();
            RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    measuredHeight * 4);
            mRecyclerView.setLayoutParams(layoutParams);
        }
    }

    /**
     * @date: 2020/9/7
     * @author: chengDa
     * @description: 计算条目高度
     */
    public int getScollYDistance() {
        LinearLayoutManager layoutManager = (LinearLayoutManager) this.mRecyclerView.getLayoutManager();
        assert layoutManager != null;
        int position = layoutManager.findFirstVisibleItemPosition();
        View firstVisiableChildView = layoutManager.findViewByPosition(position);
        int itemHeight = firstVisiableChildView.getHeight();
        return (position) * itemHeight - firstVisiableChildView.getTop();
    }

//    /**
//     * @date: 2020/9/8
//     * @author: chengDa
//     * @description: 新消息显示/隐藏
//     */
//    private void isVisibleMessage(boolean isVisible) {
//        if (isVisible) {
//            mTextView.setVisibility(View.VISIBLE);
//        } else {
//            mTextView.setVisibility(View.GONE);
//        }
//    }

}